package com.dcy.system.filter.wrapper;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
    /**
     * 存储body数据字符串格式的容器
     */
    private final String bodyStr;

    /**
     * 存储body数据的容器
     */
    private final ByteArrayInputStream inputStream;

    private final BufferedReader reader;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        final byte[] body = IoUtil.readBytes(request.getInputStream());
        bodyStr = new String(body, getCharacterEncoding());
        inputStream = new ByteArrayInputStream(body);
        reader = new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 获取请求Body
     *
     * @param request request
     * @return String
     */
    public String getBodyString(final ServletRequest request) throws IOException {
        final byte[] body = IoUtil.readBytes(request.getInputStream());
        return new String(body, getCharacterEncoding());
    }

    /**
     * 获取请求Body
     *
     * @return String
     */
    public String getBodyString() {
        return bodyStr;
    }

    @Override
    public String getCharacterEncoding() {
        String enc = super.getCharacterEncoding();
        return (enc != null ? enc : StandardCharsets.UTF_8.name());
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return reader;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return inputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}
